package com.kehutong.charge.util;

import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;


public class ImageUtil {

    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 将远程图片转换为base64格式
     * @param imageUrl：图片路径，原图大小上限，当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static File downloadImage2File(String imageUrl,long sizeLimit){
        if(sizeLimit ==0){
            //图片大小（K）
            sizeLimit = 2000L;
        }
        sizeLimit = sizeLimit * 1024;
        String base64Image;
        DataInputStream dataInputStream = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        FileOutputStream outputFileStream = null;
        File file = null;
        try {
            //从远程读取图片
            URL url = new URL(imageUrl.replaceAll("\r|\n",""));
            dataInputStream = new DataInputStream(url.openStream());
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            byte[] context = outputStream.toByteArray();

            //将图片数据还原为图片
            inputStream = new ByteArrayInputStream(context);
            BufferedImage image = ImageIO.read(inputStream);
            int imageSize = context.length;
            int type = image.getType();
            int height = image.getHeight();
            int width = image.getWidth();

            BufferedImage tempImage;
            //判断文件大小是否大于size,循环压缩，直到大小小于给定的值
            while (imageSize > sizeLimit) {
                //将图片长宽压缩到原来的90%
                height = new Double(height * 0.9).intValue();
                width = new Double(width * 0.9).intValue();
                tempImage = new BufferedImage(width, height, type);
                // 绘制缩小后的图
                tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
                //重新计算图片大小
                outputStream.reset();
                ImageIO.write(tempImage, "JPEG", outputStream);
                imageSize = outputStream.toByteArray().length;
            }

            //将图片转化为base64并返回
            byte[] data = outputStream.toByteArray();
            String jpgName = System.currentTimeMillis()+".jpg";
            file = new File(jpgName);
            outputFileStream = new FileOutputStream(file);
            outputFileStream.write(data);

        } catch (IOException e) {
            logger.error("[ImageUtil]convert error",e);
            throw new RuntimeException("获取图片失败");
        } finally {
            try {
                if (outputFileStream != null) {
                    outputFileStream.flush();
                    outputFileStream.close();
                }
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                file.deleteOnExit();
            } catch (IOException e) {
                logger.error("[ImageUtil]close error",e);
                throw new RuntimeException("获取图片失败");
            }
        }
        return file;
    }
}
